package com.atgouwu.scmall.order.controller;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.*;

import com.alibaba.fastjson2.JSON;
import com.atgouwu.scmall.order.feign.MemberFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.atgouwu.scmall.order.entity.OrderEntity;
import com.atgouwu.scmall.order.service.OrderService;
import com.atgouwu.scmall.common.utils.PageUtils;
import com.atgouwu.scmall.common.utils.R;

/**
 * 订单
 *
 * @author heran
 * @email sunlightcs@gmail.com
 * @date 2025-10-27 18:45:38
 */
@RestController
@RequestMapping("order/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 整合OpenFeign: http://localhost:9003/order/order/orderToMember?id=1
     */
    @GetMapping("/orderToMember")
    public R orderToMember(@RequestParam("id") String id) {
        R res = memberFeignService.orderTOMember(id); //远程调用member服务
        return R.ok().put("data", res);
    }

    /**
     * 整合redis:
     */
    @GetMapping("/redis")
    public R redis(@RequestParam("id") Long id) {
        String res = orderService.jetCache(id);
        return R.ok().put("data", res);
    }

    /**
     * 整合rabbitMq:
     */
    @GetMapping("/rabbitMq")
    public R rabbitMq(@RequestParam("id") Long id) {
        String res = orderService.rabbitMq(id);
        return R.ok().put("data", res);
    }

    /**
     * Kafka消息队列: 发送消息,监听(接收消息) http://localhost:9004/middleware/kafka/kafka?id=1
     *               1.pom.xml依赖:
     *               2.application.yml配置: kafka连接地址(端口号)
     *               3.创建config/KafkaConfig配置类:
     *               4.ServiceImpl实现类: kafkaTemplate同步或异步发送消息, @KafkaListener注解监听(接收消息)
     */
    @RequestMapping("/kafka")
    public R kafka(@RequestParam("id") Long id) {
        String res = orderService.kafka(id);
        return R.ok().put("data", res);
    }

    /**
     * 多线程(池): 多个线程完成同一件事(用工具发送大量请求测), http://localhost:9007/highconcurrency/thread/threadPoolExecutor
     *         1.创建config/ThreadConfig配置类:
     *           创建config/ThreadPoolConfigProperties属性类:
     *         2.application.yml配置: 线程池参数值
     *         3.Controller类: 代码
     */
    @GetMapping("/threadPoolExecutor")
    public R threadPoolExecutor(@RequestParam Map<String, Object> params) throws ExecutionException, InterruptedException {
        //pool.execute(new MyRunnable()); //无返回值
        Future<String> future = threadPoolExecutor.submit(new Callable<String>() { //有返回值
            @Override
            public String call() {
                //System.out.println("threadId:"+Thread.currentThread().getId());
                //业务代码
                return JSON.toJSONString("page");
            }
        });
        String res = future.get(); //获取返回值
        threadPoolExecutor.shutdownNow(); //关闭线程
        //System.out.println(System.currentTimeMillis() + ":" + res);
        return R.ok().put("data", res);
    }

    /**
     * 异步编程(线程池): 一个或多个线程异步完成多件事, http://localhost:9007/highconcurrency/thread/asyncProgram
     */
    @GetMapping("/asyncProgram")
    public R asyncProgram(@RequestParam Map<String, Object> params) throws ExecutionException, InterruptedException {
        //任务1: 无返回值
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(()->{ //无返回值
            //业务代码
            System.out.println("任务1:" + "page");
        }, threadPoolExecutor);
        //任务2: 有返回值
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(()->{ //有返回值
            //业务代码
            System.out.println("任务2:" + "page");
            return 1;
        }, threadPoolExecutor).whenComplete((res, exception)->{ //感知成功或异常,不能修改结果
            System.out.println("任务2不能修改结果");
        }).exceptionally(throwable->{ //感知异常,可修改结果
            System.out.println("任务2异常并修改结果");
            return 0;
        }).handle((res, exception)->{ //感知成功或异常,可修改结果
            System.out.println("任务2修改结果");
            if(res!=null) return 1;
            if(exception!=null) return 0;
            return res+10;
        });
        int i = future2.get(); //阻塞方法(获取任务2的结果)
        //任务3: 有返回值+串行化(任务3完成后,才执行任务4)
        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(()->{ //有返回值+串行化(任务3完成后,才执行任务4)
            //业务代码
            System.out.println("任务3:" + "page");
            return 1;
        }, threadPoolExecutor).thenRunAsync(()->{ //任务4新线程,不能获取3的结果,无返回,(影响下面res为null)
            //业务代码
            System.out.println("任务4:不能获取3的结果");
        }, threadPoolExecutor).thenAcceptAsync((res->{ //能获取3的结果,无返回值,(影响下面res为null)
            //业务代码
            System.out.println("任务4:能获取3的结果"+res);
        }), threadPoolExecutor).thenApplyAsync(res->{ //能获取3的结果,且返回本任务4结果
            System.out.println("任务4:获取3的结果,且返回本任务4结果"+res);
            return 2;
        }, threadPoolExecutor);
        int is = future3.get(); //阻塞方法(获取任务3的结果)
        //方式1: 全部任务完成
        CompletableFuture<Void> allOf = CompletableFuture.allOf(future1, future2, future3);  //组合所有任务,全部完成后返回值
        allOf.get(); //阻塞方法(全部任务完成)
        //方式2: 任一任务完成
        //CompletableFuture<Object> anyOf = CompletableFuture.anyOf(future1, future2, future3); //任意一个完成返回值
        //Object object = anyOf.get(); //阻塞方法(任一任务完成)
        System.out.println("任务完成:"+i+","+is);
        return R.ok().put("data", i+","+is);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = orderService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		OrderEntity order = orderService.getById(id);
        return R.ok().put("order", order);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody OrderEntity order){
		orderService.save(order);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody OrderEntity order){
		orderService.updateById(order);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		orderService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

}
